package cn.hsa.fqz.task.service.impl;

import cn.hsa.fqz.task.entity.TSysOrg;
import cn.hsa.fqz.task.dao.TSysOrgMapper;
import cn.hsa.fqz.task.service.ISysOrgService;
import cn.hsa.fqz.task.service.dto.RegionDTO;
import cn.hsa.fqz.task.service.dto.TreeDTO;
import cn.hsa.fqz.util.TreeUtil;
import cn.hsa.hsaf.core.framework.web.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 丁志敏
 * @version v1.0
 * @apiNote 功能描述:()
 * @date create in 2022/9/13 11:37
 */
@Slf4j
@Service
public class SysOrgServiceImpl implements ISysOrgService {
    @Autowired
    private TSysOrgMapper orgMapper;

    @Override
    public List<TSysOrg> getProviceOrg(){
        return orgMapper.getAllProviceOrgs();
    }

    @Override
    public List<TreeDTO> getOrgTree(String uid) {
        //查询当前用户权限
        TSysOrg sysOrg = orgMapper.selectByUserId(uid);
        if (sysOrg == null) {
            throw new AppException(-1, "当前用户未绑定机构");
        }
        List<TSysOrg> list = orgMapper.getRegionsByParentId(sysOrg.getOrgId());
        if(!CollectionUtils.isEmpty(list)){
            list.add(sysOrg);
        }
        List<RegionDTO> regions = list.stream().map(i->{
            RegionDTO region = new RegionDTO();
            region.setId(i.getOrgId());
            region.setRegion(i.getOrgCode());
            region.setRegionName(i.getOrgName());
            region.setTitle(i.getOrgName());
            region.setType(i.getState()+"");
            region.setPid(i.getPid());
            return region;
        }).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(list)) {
            TreeDTO root = new TreeDTO(sysOrg.getPid());
            TreeDTO vo = new TreeUtil(root, new ArrayList<>(regions)).build();
            return vo.getChildren();
        }
        return new ArrayList<>();
    }
}
